package com.niodata.dp.web;

import com.niodata.dp.core.ConfigurationKeys;
import com.niodata.dp.core.DpConfiguration;
import com.niodata.dp.web.module.base.BaseController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("CommonController")
public class CommonController extends BaseController {

  @RequestMapping({"/login"})
  public String logIn(HttpServletRequest request) {
    String referrer = request.getHeader("Referer");
    request.getSession().setAttribute("url_prior_login", referrer);
    request.getSession().setAttribute("login_type", "browser");
    //String secMode = DpConfiguration.getString(ConfigurationKeys.SECURITY_AUTH_MODE, "jdbc");
    return "/#/login";
  }

  /**
   * 代替错误信息白板页.
   *
   * @param code HttpStatus错误码
   * @param message HttpStatus错误内容
   * @return Object-JSON
   */
  @RequestMapping("/dpError")
  @ResponseBody
  public Object error(@RequestParam int code, @RequestParam String message) {
    return getError(code, message);
  }

  @RequestMapping("/logout")
  public void logOut(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    if (session != null) {
      session.invalidate();
    }
    if ("cas".equals(DpConfiguration.getString(ConfigurationKeys.SECURITY_AUTH_MODE,
          null))) {
      String casLogOut = DpConfiguration.getString("cas.server-logout-url");
      response.sendRedirect(casLogOut);
    } else {
      response.sendRedirect("/#/login");
    }
  }
}
